package com.hunttown.common.dao.base;

import com.hunttown.common.dao.sequence.Sequences;
import com.hunttown.common.dao.transaction.TransactionManagers;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.util.Assert;

public abstract class BaseService implements ApplicationContextAware {
    static TransactionManagers transactionManagers;
    Sequences sequences;

    public BaseService() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (transactionManagers == null) {
            transactionManagers = (TransactionManagers) applicationContext.getBean("transactionManagers", TransactionManagers.class);
            Assert.notNull(transactionManagers, "must define an TransactionManagers type bean, name : transactionManagers");
        }

        if (applicationContext.containsBeanDefinition("defaultSequences")) {
            this.sequences = (Sequences) applicationContext.getBean("defaultSequences", Sequences.class);
        }

        if (this.sequences == null) {
            Map<String, Sequences> sequencesMap = applicationContext.getBeansOfType(Sequences.class);
            if (sequencesMap.size() == 1) {
                this.sequences = (Sequences) sequencesMap.values().iterator().next();
            }
        }

    }

    public Sequences getSequences() {
        return this.sequences;
    }

    public void setSequences(Sequences sequences) {
        this.sequences = sequences;
    }

    public <T> T executeInTrans(TransactionCallback<T> callback, IBaseDao... daoArray) {
        return transactionManagers.executeInTrans(callback, daoArray);
    }
}